<script setup>
import { onUnmounted, ref } from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'
import { listMarker } from '@/api/dashboard/marker'
import useClipboard from 'vue-clipboard3'
import { getJSON } from './tiantai.js'

const { toClipboard } = useClipboard()
const position = ref('')
let map = null
let contextMenuPositon = null

// 点标记显示内容，HTML要素字符串
function markerContent(str, background) {
  return `<div class="custom-marker" style="background: url('/api/profile/upload/assets/${background}.png');">${str}</div>`
}

onUnmounted(() => {
  map?.destroy()
})
const init = (mapData) => {
  AMapLoader.load({
    key: '1fc51b0c951aeb41e426d47acd1aaee6', // 申请好的Web端开发者Key，首次调用 load 时必填
    version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: ['AMap.GeoJSON'], // 需要加载的插件
  })
    .then((AMap) => {
      map = new AMap.Map('map-container', {
        viewMode: '3D', // 是否为3D地图模式
        zoom: mapData.zoom, // 初始化地图级别
        center: mapData.center.split(','), // 初始化地图中心点位置
        // layers
      })
      // 构造官方卫星、路网图层
      var satelliteLayer = new AMap.TileLayer.Satellite()
      var roadNetLayer = new AMap.TileLayer.RoadNet()
      //批量添加图层
      map.add([satelliteLayer, roadNetLayer])
      map.remove(roadNetLayer)
      contextMap() //右键菜单
      clickMap() //点击地图获取坐标
      addMarks() //添加文本标记
      // var geojson = new AMap.GeoJSON({
      //   geoJSON: getJSON(),
      // })
      // map.add(geojson)
    })
    .catch((e) => {
      console.log(e)
    })
}
defineExpose({
  init,
})
const emit = defineEmits([
  'addMarker',
  'delMarker',
  'updateMarker',
  'setCenter',
])
const addMarks = () => {
  listMarker().then((res) => {
    let markers = res.rows
    markers.forEach((item) => {
      var marker = new AMap.Marker({
        position: item.position.split(','),
        content: markerContent(item.name, item.background),
      })
      if (item.type == 1) {
        marker.on('click', function (e) {
          dialogType.value = 1
          dialogVisible.value = true
          dialogImageUrl.value =
            import.meta.env.VITE_APP_BASE_API + item.content
        })
      } else if (item.type == 2) {
        marker.on('click', function (e) {
          window.open('//' + item.content)
        })
      } else if (item.type == 3) {
        marker.on('click', function (e) {
          dialogType.value = 3
          dialogVisible.value = true
          dialogContent.value = item.content
        })
      }
      var contextMenuMarker = new AMap.ContextMenu()
      contextMenuMarker.addItem(
        '修改',
        function () {
          emit('updateMarker', item)
        },
        0
      )
      contextMenuMarker.addItem(
        '删除',
        function () {
          emit('delMarker', item)
        },
        1
      )
      marker.on('rightclick', function (e) {
        contextMenuMarker.open(map, e.lnglat)
      })
      map.add(marker)
    })
  })
}
const dialogVisible = ref(false)
const dialogType = ref(null)
const dialogContent = ref('')
const dialogImageUrl = ref('')
const clickMap = (e) => {
  map.on('click', function (e) {
    position.value = e.lnglat.toString()
    toClipboard(e.lnglat.toString())
  })
}
const contextMap = () => {
  //创建右键菜单
  var contextMenu = new AMap.ContextMenu()
  contextMenu.addItem(
    '添加标记',
    function (e) {
      emit('addMarker', contextMenuPositon)
      contextMenu.close()
    },
    0
  )
  contextMenu.addItem(
    '设置为中心点',
    function (e) {
      emit('setCenter', contextMenuPositon)
      contextMenu.close()
    },
    1
  )
  contextMenu.addItem(
    '设置当前为地图默认缩放倍率',
    function (e) {
      emit('setMapScale', map.getZoom())
      contextMenu.close()
    },
    2
  )
  //地图绑定鼠标右击事件——弹出右键菜单
  map.on('rightclick', function (e) {
    contextMenu.open(map, e.lnglat)
    contextMenuPositon = e.lnglat
  })
}
</script>

<template>
  <div id="map">
    <div id="map-container"></div>
    <div class="position">
      坐标结果 ：
      <el-input
        v-model="position"
        readonly
        style="width: 240px"
        placeholder="点击地图可以复制坐标"
      />
    </div>
  </div>
  <el-dialog v-model="dialogVisible" title="预览" width="800px" append-to-body>
    <img
      :src="dialogImageUrl"
      style="display: block; max-width: 100%; margin: 0 auto"
      v-if="dialogType == 1"
    />
    <div v-html="dialogContent" v-if="dialogType == 3"></div>
  </el-dialog>
</template>

<style lang="scss">
#map {
  flex-shrink: 0;
  width: 100%;
  padding: 10px;
}

#map-container {
  cursor: pointer !important;
  width: 100%;
  height: 650px;
}

.amap-logo {
  display: none;
  opacity: 0 !important;
}

.amap-copyright {
  opacity: 0;
}

.position {
  margin: 10px auto;
  display: flex;
  align-items: center;
  justify-content: center;
}

.custom-marker {
  width: 155px;
  height: 72px;
  line-height: 62px;
  text-align: center;
  color: #fff;
}
</style>
